package Cau5;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Server {
	public static void main(String[] args) throws IOException {

        int port = 5000;
        DatagramSocket sk = new DatagramSocket(port);
        DatagramPacket pk;
        boolean cont = true;
        byte[] buffer = new byte[1024];
        
        System.out.println("Server is listening on port " + port);

        while (cont) {

            pk = new DatagramPacket(buffer, buffer.length);
            sk.receive(pk);
            String sReceived = new String(pk.getData(), 0, pk.getLength());
            if (sReceived.equals("QUIT")) {
                cont = false;
            } else {
                String sResult = TimeServerProcess(sReceived);
                pk.setData(sResult.getBytes());
                sk.send(pk);
            }
        }

        sk.close();
    }

    public static String TimeServerProcess(String sReceived) {
        String sResult = "null";
        Date d = new Date();

        if (sReceived.equals("TIME")) {
            sResult = String.format("Current time: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "\n");
            return sResult;
        } else if (sReceived.equals("DATE")) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            sResult = "Current date: " + dateFormat.format(d) + "\n";
            return sResult;
        } else if (sReceived.equals("TRIPTIME")) {
            sResult = "CHUA LAM" + "\n";
            return sResult;
        }
        return sResult;
    }
}
